
package com.j2eefast.flowable.bpm.service;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.j2eefast.common.core.mutidatasource.annotaion.DataSource;
import com.j2eefast.common.core.page.Query;
import com.j2eefast.common.core.utils.PageUtil;
import com.j2eefast.common.core.utils.ValidatorUtil;
import com.j2eefast.flowable.bpm.entity.ProjectArchivesEntity;
import com.j2eefast.flowable.bpm.entity.ProjectClaimEntity;
import com.j2eefast.flowable.bpm.entity.ProjectClaimRecordEntity;
import com.j2eefast.flowable.bpm.entity.ProjectSanLianEntity;
import com.j2eefast.flowable.bpm.mapper.ClaimMapper;
import com.j2eefast.flowable.bpm.utils.StringUtils;
import com.j2eefast.framework.sys.entity.SysUserEntity;
import com.j2eefast.framework.sys.mapper.SysUserMapper;
import com.j2eefast.framework.sys.service.SysUserService;
import com.j2eefast.framework.utils.Constant;
import com.j2eefast.framework.utils.UserUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * <p></p>
 *
 * @author: zhangyuan
 * @date: 2021-04-29 23:47
 * @web: http://www.letukeji.cn
 * @version: 1.0.1
 */


@Service
//@Transactional(readOnly = true)
public class ClaimService extends ServiceImpl<ClaimMapper, ProjectClaimEntity> {

	@Resource
	protected ClaimMapper claimMapper;
	@Resource
	protected SysUserMapper sysUserMapper;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private ManagerService managerService;
	@Autowired
	private SanLianService sanLianService;
	@Autowired
	private ArchivesService archivesService;


	/**
	 * 页面展示查询翻页
	 */
	public PageUtil findPage(Map<String, Object> params) {
//		String claimStatus = (String) params.get("claimStatus");	//认领状态（0：未认领 1：未全部认领 2：已认领）
		//String arrivalTime = (String) params.get("arrivalTime");//到账日期
		String remittanceUnit = (String) params.get("remittanceUnit");	//汇款单位
		String beginTime = (String) params.get("beginTime");
		String endTime = (String) params.get("endTime");
		String arrivalAmount1 = (String) params.get("arrivalAmount1");//到账日期
		String arrivalAmount2 = (String) params.get("arrivalAmount2");//到账日期

	//	String remarks = (String) params.get("remarks");//备注附言
//		String claimAmount = (String) params.get("claimAmount");	//已领金额
//		String arrivalAmount = (String) params.get("arrivalAmount");	//到账金额
		Page<ProjectClaimEntity> page = claimMapper.findPage(	new Query<ProjectClaimEntity>(params).getPage(),
				StrUtil.nullToDefault(beginTime,""),
				StrUtil.nullToDefault(endTime,""),
				StrUtil.nullToDefault(arrivalAmount1,""),
				StrUtil.nullToDefault(arrivalAmount2,""),
				StrUtil.nullToDefault(remittanceUnit,""),
//				StrUtil.nullToDefault(claimAmount,""),
//				StrUtil.nullToDefault(arrivalAmount,""),
				(String) params.get(Constant.SQL_FILTER));
		return new PageUtil(page);
//		ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery()
//				.latestVersion().orderByProcessDefinitionKey().asc();
//
//		if (ToolUtil.isNotEmpty(category)){
//			processDefinitionQuery.processDefinitionCategory(category);
//		}
//
//		if (ToolUtil.isNotEmpty(suspensionState) && suspensionState.equals("1")){
//			processDefinitionQuery.active();
//		}
//
//		if (ToolUtil.isNotEmpty(suspensionState) && suspensionState.equals("2")){
//			processDefinitionQuery.suspended();
//		}
//
//		long count = processDefinitionQuery.count();
//		List<ProcessDefinition> processDefinitionList = processDefinitionQuery.listPage(Integer.parseInt((String) params.get("page"))-1,
//				Integer.parseInt((String) params.get("limit")));
//
//		List<ProcdefEntity> dataList = new ArrayList<>();
//		for (ProcessDefinition processDefinition : processDefinitionList) {
//			String deploymentId = processDefinition.getDeploymentId();
//			Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
//
//			ProcdefEntity reProcDef = new ProcdefEntity((ProcessDefinitionEntityImpl) processDefinition);
//
//			reProcDef.setDeploymentTime(deployment.getDeploymentTime());
//			//reProcDef.setSuspensionState(repositoryService.isProcessDefinitionSuspended(reProcDef.getId())?2:1);
//			dataList.add(reProcDef);
//		}
//		return new PageUtil(dataList,count,50,1);
	}

	/**
	 * 到账认领记录
	 * userId 用户id
	 */
	public List<ProjectClaimRecordEntity> recordList(Long userId,Long id){
		return claimMapper.recordList(userId,id);
	}

	/**
	 * 到账认领记录
	 * userId 用户id
	 */
	public ProjectClaimRecordEntity recordInfo(Long id){
		return claimMapper.recordInfo(id);
	}

	@DataSource(name="master")

	public SysUserEntity getSysById(Long ceoName){
		return sysUserMapper.getSysById(ceoName);
	}


	/**
	 * 到账认领信息
	 * id 主键
	 */
	public ProjectClaimEntity getByIds(Long id){
		return claimMapper.getByIds(id);
	}

	/**
	 * 到账认领信息更新
	 *
	 */
	public boolean updateByIds(ProjectClaimEntity taskFrom){
		BigDecimal  claimAmount=taskFrom.getClaimAmount();
		BigDecimal arrivalAmount=taskFrom.getArrivalAmount();
		if(claimAmount.compareTo(BigDecimal.ZERO)==1){
			taskFrom.setUnclaimedAmount(arrivalAmount.subtract(claimAmount));
		}
		//		设置领取状态
		if(claimAmount.compareTo(BigDecimal.ZERO)==0){
			taskFrom.setClaimStatus(0);
		}else if(arrivalAmount.compareTo(claimAmount)==0){
			taskFrom.setClaimStatus(2);
		}else
			taskFrom.setClaimStatus(1);
		int i=claimMapper.updateByIds(taskFrom);
		if(i>0){
			return true;
		}else
		return false;
	}
	/**
	 * 添加到账认领信息
	 *
	 */
	public boolean save(ProjectClaimEntity taskFrom){
		Long userId= UserUtils.getUserInfo().getId();
		BigDecimal arrivalAmount=taskFrom.getArrivalAmount();
		taskFrom.setUnclaimedAmount(arrivalAmount);
		taskFrom.setClaimStatus(0);
		taskFrom.setUserId(userId);
		String code=claimCode(taskFrom.getClaimCode());
		taskFrom.setClaimCode(code);
		int i=claimMapper.save(taskFrom);
		if(i>0){
			return true;
		}else
			return false;
	}
	/**
	 * 添加到账认领记录
	 *
	 */
	public boolean saveRecord(List<ProjectClaimRecordEntity> recordList){

		return claimMapper.saveRecord(recordList);
//		if(i>0){
//			return true;
//		}else
//			return false;
	}

//	public boolean saveRecord(HttpServletRequest request) throws ParseException {
//		List<ProjectClaimRecordEntity> recordList = new ArrayList<ProjectClaimRecordEntity>();//更新数据放这里面
//		List<ProjectClaimRecordEntity> recordList1 = new ArrayList<ProjectClaimRecordEntity>();//新增数据放这里
//		Long claimId = Long.parseLong(request.getParameter("claimId"));//认领id
//		Long userId = Long.parseLong(request.getParameter("userId"));//用户id
//		BigDecimal arrivalAmount=StringUtils.StringDecimal(request.getParameter("arrivalAmount"));//总金额
//		BigDecimal sum = new BigDecimal("0.00");
//		String total_items = request.getParameter("total_items");//认领插入条数
//		ValidatorUtil.validateEntity(total_items);
//		int total = Integer.valueOf(total_items);
//		for (int i = 1; i <= total; i++) {
//			String id = "id_" + i;
//			String nameId = "nameId_" + i;
//			String fileId = "fileId_" + i;
//			String sanlianId = "sanlianId_" + i;
//			String claimType = "claimType_" + i;
//			String openDepartment = "openDepartment_" + i;
//			String claimTime = "claimTime_" + i;
//			String remarks = "remarks_" + i;
//			String putAmount = "putAmount_" + i;
//			String claimNumber = "claimNumber_" + i;
//			Date date = new Date();//创建一个时间对象，获取到当前的时间
//			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//注意月份是MM
//			ProjectClaimRecordEntity user = new ProjectClaimRecordEntity();
//			user.setNameId(Long.parseLong(request.getParameter(nameId)));
//			user.setSanlianId(Long.parseLong(request.getParameter(sanlianId)));
//			user.setFileId(Long.parseLong(request.getParameter(fileId)));
//			user.setClaimType(request.getParameter(claimType));
//			user.setClaimTime(simpleDateFormat.parse(request.getParameter(claimTime)));
//			user.setOpenDepartment(request.getParameter(openDepartment));
//			user.setRemarks(request.getParameter(remarks));
//			//user.setClaimNumber(Double.valueOf(request.getParameter(claimNumber)));
//			user.setPutAmount(StringUtils.StringDecimal(request.getParameter(putAmount)));
//			user.setClaimId(claimId);
//			user.setUserId(userId);
//			sum=sum.add(user.getPutAmount());
//			SysUserEntity userEntity = this.getSysById(Long.parseLong(request.getParameter(nameId)));
//			//	ProjectSanLianEntity sanlianEntity = sanLianService.getSanlianById(Long.parseLong(request.getParameter(sanlianId)));
//			ProjectSanLianEntity sanlianEntity = sanLianService.getSanlianId();
//			ProjectArchivesEntity fileEntity = archivesService.getArchivesById(Long.parseLong(request.getParameter(fileId)));
//			if(userEntity!=null){
//				user.setCeoName(userEntity.getName());
//			}
//			if(sanlianEntity!=null){
//				user.setSanlianNo(sanlianEntity.getName());
//			}
//			if(fileEntity!=null){
//				user.setFileNumber(fileEntity.getName());
//			}
//			if (request.getParameter(id) != "") {
//				user.setId(Long.parseLong(request.getParameter(id)));
//			}
//			//先去查询是否有记录
//			ProjectClaimRecordEntity info = claimMapper.recordInfo(user.getId());
//			if (info != null) {
//				recordList.add(user);
//			} else
//				recordList1.add(user);
//
//		}
//		//1:先查询数据库是否有数据
//		// 2：如果有先更新
//		//3：没有插入
//		ProjectClaimEntity projectClaimEntity = claimMapper.getByIds(claimId);//获取认领管理信息
//		System.out.println(sum);
//		projectClaimEntity.setClaimAmount(sum);//已领金额
//		projectClaimEntity.setUnclaimedAmount(arrivalAmount.subtract(sum));//未领金额
//		boolean claimEntity =this.updateByIds(projectClaimEntity);
//		ValidatorUtil.validateEntity(claimEntity);
////		if(claimEntity==false){
////			return this.error("修改失败!");
////		}
//		if (recordList != null && !recordList.isEmpty()) {
//			boolean record = this.updateRecord(recordList);
//			System.out.println(claimEntity);
//			if(record!=true){
//				return false;
//			}
//			else if (recordList1 != null && !recordList1.isEmpty()) {
//				System.out.println("44444444444");
//				return claimMapper.saveRecord(recordList1);
//			}
//			else {
//				System.out.println("55555555555");
//				return true;
//			}
//		} else {
//			return claimMapper.saveRecord(recordList1);
//		}
////		int i=claimMapper.saveRecord(recordList);
////		if(i>0){
////			return true;
////		}else
////			return false;
//	}
	/**
	 * 查询用户名称
	 *
	 */
//	@DataSource(name = "master")
//	public List<SysUserEntity> getSysById(List<ProjectClaimRecordEntity> ceoList){
//			return claimMapper.getSysById(ceoList);
//	}
//	public SysUserEntity getSysById(Long ceoName){
//		return claimMapper.getSysById(ceoName);
//	}
	/**
	 * 添加到账认领记录
	 *
	 */
	public boolean updateRecord(List<ProjectClaimRecordEntity> recordList){
		int i=claimMapper.updateRecord(recordList);
		if(i>0){
			return true;
		}else
			return false;
	}
//	public boolean deleteRecord(Long id){
//
//		return claimMapper.deleteRecord(id);
//	}

	public  boolean deleteRecord(HttpServletRequest request){
		String total_items = request.getParameter("total_items");//认领插入条数
		Long claimId = Long.parseLong(request.getParameter("claimId"));//认领id
		Long userId = Long.parseLong(request.getParameter("userId"));//用户id
		String str = request.getParameter("itemsToRemove");//删除的行的ID信息
		ValidatorUtil.validateEntity(total_items);
		int total = Integer.valueOf(total_items);
		List<ProjectClaimRecordEntity> recordEntity = this.recordList(userId, claimId);//获取认领金额信息记录
		//批量删除 先不考虑性能
		if (str != "" && recordEntity != null) {
			String[] arr = str.split(","); // 用,分割
			for (int i = 0; i < arr.length; i++) {
				for (int j = 0; j < recordEntity.size(); j++) {
					System.out.println(str != "");
					if (Long.parseLong(arr[i]) == recordEntity.get(j).getId()) {
						claimMapper.deleteRecord(recordEntity.get(j).getId());
					}
				}
			}
			return true;
		}else
		return false;
		//return claimMapper.deleteRecord(id);
	}



	public boolean deleteClaim(Long[] ids){
		return claimMapper.deleteClaim(ids);
	}

	/**
	 * 生成编号
	 * @param s
	 * @return
	 */
	public String claimCode(String s) {
//		int id = ParamUtils.getInt(s, "-", 0);
	// 对当前日期进行格式化
	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmSS");
	String date = sdf.format(new Date());
	//DecimalFormat dft = new DecimalFormat(FORMAT_CODE);
	StringUtils ParamUtils = new StringUtils();

	if (s != "" && s != null) {
		String[] str = s.split("-");
		int[] num = new int[str.length];
		for (int i = 0; i < num.length; i++) {
			num[i] = Integer.parseInt(str[i]);
		}
		int i = num[num.length - 1];
		StringBuilder builder = new StringBuilder();
		builder.append("RL-");
		builder.append(date);
		builder.append("-");
		builder.append(i + 1);
		//String code = ParamUtils.getConteactNo(date, i);
		return builder.toString();
	} else {
		int num = 1;
		StringBuilder builder = new StringBuilder();
		builder.append("RL-");
		builder.append(date);
		builder.append("-");
		builder.append(num);
		//String code = ParamUtils.getConteactNo(date, i);
		return builder.toString();
	}


}



//	/**
//	 * 前端数据处理
//	 * @param request
//	 * @return
//	 */
//	public List<ProjectClaimRecordEntity> setParams(HttpServletRequest request) throws ParseException {
//		Long claimId = Long.parseLong(request.getParameter("claimId"));//认领id
//		Long userId = Long.parseLong(request.getParameter("userId"));//用户id
//		String total_items = request.getParameter("total_items");//认领插入条数
//		ValidatorUtil.validateEntity(total_items);
//		int total = Integer.valueOf(total_items);
//		List<ProjectClaimRecordEntity> recordList = new ArrayList<ProjectClaimRecordEntity>();//更新数据放这里面
//		List<ProjectClaimRecordEntity> recordList1 = new ArrayList<ProjectClaimRecordEntity>();//新增数据放这里
//		BigDecimal arrivalAmount=StringUtils.StringDecimal(request.getParameter("arrivalAmount"));//总金额
//		BigDecimal sum = new BigDecimal("0.00");
//		for (int i = 1; i <= total; i++) {
//			String id = "id_" + i;
//			String nameId = "nameId_" + i;
//			String fileId = "fileId_" + i;
//			String sanlianId = "sanlianId_" + i;
//			String claimType = "claimType_" + i;
//			String openDepartment = "openDepartment_" + i;
//			String claimTime = "claimTime_" + i;
//			String remarks = "remarks_" + i;
//			String putAmount = "putAmount_" + i;
//			String claimNumber = "claimNumber_" + i;
//			Date date = new Date();//创建一个时间对象，获取到当前的时间
//			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//注意月份是MM
//			ProjectClaimRecordEntity user = new ProjectClaimRecordEntity();
//			user.setNameId(Long.parseLong(request.getParameter(nameId)));
//			user.setSanlianId(Long.parseLong(request.getParameter(sanlianId)));
//			user.setFileId(Long.parseLong(request.getParameter(fileId)));
//			user.setClaimType(request.getParameter(claimType));
//			user.setClaimTime(simpleDateFormat.parse(request.getParameter(claimTime)));
//			user.setOpenDepartment(request.getParameter(openDepartment));
//			user.setRemarks(request.getParameter(remarks));
//			//user.setClaimNumber(Double.valueOf(request.getParameter(claimNumber)));
//			user.setPutAmount(StringUtils.StringDecimal(request.getParameter(putAmount)));
//			user.setClaimId(claimId);
//			user.setUserId(userId);
//			sum=sum.add(user.getPutAmount());
//			SysUserEntity userEntity = sysUserService.getSysById(Long.parseLong(request.getParameter(nameId)));
//			//	ProjectSanLianEntity sanlianEntity = sanLianService.getSanlianById(Long.parseLong(request.getParameter(sanlianId)));
//			ProjectSanLianEntity sanlianEntity = sanLianService.getSanlianId();
//			ProjectArchivesEntity fileEntity = archivesService.getArchivesById(Long.parseLong(request.getParameter(fileId)));
//			if(userEntity!=null){
//				user.setCeoName(userEntity.getName());
//			}
//			if(sanlianEntity!=null){
//				user.setSanlianNo(sanlianEntity.getName());
//			}
//			if(fileEntity!=null){
//				user.setFileNumber(fileEntity.getName());
//			}
//			if (request.getParameter(id) != "") {
//				user.setId(Long.parseLong(request.getParameter(id)));
//			}
//			//先去查询是否有记录
//			ProjectClaimRecordEntity info = this.recordInfo(user.getId());
//			if (info != null) {
//				recordList.add(user);
//			} else
//				recordList1.add(user);
//		}
//
//	}



}
